package com.qezhhnjy.demo.hadoop.pool;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;

/**
 * @author zhaoyangfu - 2021/2/4 12:56
 */
@EqualsAndHashCode(callSuper = true)
@Slf4j
@Data
public class HadoopFactory extends BasePooledObjectFactory<FileSystem> {

    private static final Path root = new Path("/");

    private Configuration configuration;

    @Override
    public FileSystem create() throws Exception {
        return FileSystem.get(configuration);
    }

    @Override
    public PooledObject<FileSystem> wrap(FileSystem obj) {
        return new DefaultPooledObject<>(obj);
    }

    @Override
    public void destroyObject(PooledObject<FileSystem> p) throws Exception {
        FileSystem fs = p.getObject();
        if (fs != null) fs.close();
    }

    @Override
    public boolean validateObject(PooledObject<FileSystem> p) {
        try {
            return p.getObject().exists(root);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    @Override
    public void activateObject(PooledObject<FileSystem> p) throws Exception {
        super.activateObject(p);
    }

    @Override
    public void passivateObject(PooledObject<FileSystem> p) throws Exception {
        super.passivateObject(p);
    }
}
